# -*- coding: utf-8 -*-
import pymysql.cursors

from douban_mysql.settings import mysql_host, mysql_port, mysql_user, mysql_password, mysql_db_name


# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


class DoubanMysqlPipeline(object):
    def __init__(self):
        self.connect = pymysql.connect(
            host=mysql_host,  # 数据库地址
            port=mysql_port,  # 数据库端口
            db=mysql_db_name,  # 数据库名
            user=mysql_user,  # 数据库用户名
            passwd=mysql_password,  # 数据库密码
            charset='utf8',  # 编码方式
            use_unicode=True)

        # 通过cursor执行增删查改
        self.cursor = self.connect.cursor()

    def process_item(self, item, spider):
        self.cursor.execute(
           "insert into douban_movie(serial_number, movie_name, introduce, star, evaluate, slogan) values(%s, %s, %s, %s, %s, %s)",
            # 纯属python操作mysql知识，不熟悉请恶补
            (item['serial_number'],  # item里面定义的字段和表字段对应
             item['movie_name'],
             item['introduce'],
             item['star'],
             item['evaluate'],
             item['slogan']))

        self.connect.commit()
        return item
